package com.yjq.programmer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjq.programmer.bean.CodeMsg;
import com.yjq.programmer.dao.*;
import com.yjq.programmer.domain.*;
import com.yjq.programmer.dto.MusicDTO;
import com.yjq.programmer.dto.MusicMenuDTO;
import com.yjq.programmer.dto.PageDTO;
import com.yjq.programmer.dto.ResponseDTO;
import com.yjq.programmer.service.IMusicService;
import com.yjq.programmer.utils.CommonUtil;
import com.yjq.programmer.utils.CopyUtil;
import com.yjq.programmer.utils.UuidUtil;
import com.yjq.programmer.utils.ValidateEntityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨杨吖
 * @QQ 823208782
 * @WX yjqi12345678
 * @create 2022-11-12 15:42
 */
@Service
@Transactional
public class MusicServiceImpl implements IMusicService {

    @Resource
    private MusicMapper musicMapper;

    @Resource
    private AlbumMapper albumMapper;

    @Resource
    private SingerMapper singerMapper;

    @Resource
    private MusicMenuItemMapper musicMenuItemMapper;

    @Resource
    private CollectMapper collectMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private RecentListenMapper recentListenMapper;

    @Resource
    private LyricsMapper lyricsMapper;

    /**
     * 分页获取音乐数据
     * @param pageDTO
     * @return
     */
    @Override
    public ResponseDTO<PageDTO<MusicDTO>> getMusicListByPage(PageDTO<MusicDTO> pageDTO) {
        MusicExample musicExample = new MusicExample();
        // 判断是否进行关键字搜索
        MusicDTO searchMusicDTO = pageDTO.getSearchEntity();
        MusicExample.Criteria criteria = musicExample.createCriteria();
        if(!CommonUtil.isEmpty(searchMusicDTO.getName())) {
            criteria.andNameLike("%" + searchMusicDTO.getName() + "%");
        }
        musicExample.setOrderByClause("create_time desc");
        // select * from music where name like %?%
        // 不知道当前页多少，默认为第一页
        if(pageDTO.getPage() == null){
            pageDTO.setPage(1);
        }
        if(pageDTO.getSize() == null) {
            pageDTO.setSize(5);
        }
        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        // 分页查出音乐数据
        List<Music> musicList = musicMapper.selectByExample(musicExample);
        PageInfo<Music> pageInfo = new PageInfo<>(musicList);
        // 获取数据的总数
        pageDTO.setTotal(pageInfo.getTotal());
        // 将domain类型数据  转成 DTO类型数据
        List<MusicDTO> musicDTOList = CopyUtil.copyList(musicList, MusicDTO.class);
        pageDTO.setList(musicDTOList);
        return ResponseDTO.success(pageDTO);
    }

    /**
     * 保存音乐数据(添加、修改)
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> saveMusic(MusicDTO musicDTO) {
        // 进行统一表单验证
        CodeMsg validate = ValidateEntityUtil.validate(musicDTO);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDTO.errorByMsg(validate);
        }
        Music music = CopyUtil.copy(musicDTO, Music.class);
        Album album = albumMapper.selectByPrimaryKey(music.getAlbumId());
        if(album == null) {
            return ResponseDTO.errorByMsg(CodeMsg.ALBUM_NOT_EXIST);
        }
        music.setAlbumName(album.getName());
        Singer singer = singerMapper.selectByPrimaryKey(music.getSingerId());
        if(singer == null) {
            return ResponseDTO.errorByMsg(CodeMsg.SINGER_NOT_EXIST);
        }
        music.setSingerName(singer.getName());
        if(CommonUtil.isEmpty(music.getId())){
            // id为空 说明是添加数据
            // 生成8位id
            music.setId(UuidUtil.getShortUuid());
            music.setCreateTime(new Date());
            // 添加数据到数据库
            if(musicMapper.insertSelective(music) == 0){
                return ResponseDTO.errorByMsg(CodeMsg.MUSIC_ADD_ERROR);
            }
        }else{
            // id不为空 说明是修改数据
            // 修改数据库中数据
            if(musicMapper.updateByPrimaryKeySelective(music) == 0){
                return ResponseDTO.errorByMsg(CodeMsg.MUSIC_EDIT_ERROR);
            }
        }
        return ResponseDTO.successByMsg(true, "保存成功！");
    }

    /**
     * 删除音乐数据
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> removeMusic(MusicDTO musicDTO) {
        if(CommonUtil.isEmpty(musicDTO.getId())){
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        // 删除音乐信息
        if(musicMapper.deleteByPrimaryKey(musicDTO.getId()) == 0){
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_DELETE_ERROR);
        }
        // 删除与音乐有关的收藏信息
        CollectExample collectExample =  new CollectExample();
        collectExample.createCriteria().andMusicIdEqualTo(musicDTO.getId());
        collectMapper.deleteByExample(collectExample);
        // 删除与该音乐有关的评论信息
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andMusicIdEqualTo(musicDTO.getId());
        commentMapper.deleteByExample(commentExample);
        // 删除与该音乐有关的最近播放信息
        RecentListenExample recentListenExample = new RecentListenExample();
        recentListenExample.createCriteria().andMusicIdEqualTo(musicDTO.getId());
        recentListenMapper.deleteByExample(recentListenExample);
        // 删除与该音乐有关的歌词信息
        LyricsExample lyricsExample = new LyricsExample();
        lyricsExample.createCriteria().andMusicIdEqualTo(musicDTO.getId());
        lyricsMapper.deleteByExample(lyricsExample);
        // 删除与该音乐有关的歌单详情信息
        MusicMenuItemExample musicMenuItemExample = new MusicMenuItemExample();
        musicMenuItemExample.createCriteria().andMusicIdEqualTo(musicDTO.getId());
        musicMenuItemMapper.deleteByExample(musicMenuItemExample);
        return ResponseDTO.successByMsg(true, "删除成功！");
    }

    /**
     * 根据专辑id获取音乐数据
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getMusicListByAlbumId(MusicDTO musicDTO) {
        if(CommonUtil.isEmpty(musicDTO.getAlbumId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicExample musicExample = new MusicExample();
        musicExample.createCriteria().andAlbumIdEqualTo(musicDTO.getAlbumId());
        List<Music> music = musicMapper.selectByExample(musicExample);
        return ResponseDTO.success(CopyUtil.copyList(music, MusicDTO.class));
    }

    /**
     * 根据id获取音乐数据
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<MusicDTO> getMusicById(MusicDTO musicDTO) {
        if(CommonUtil.isEmpty(musicDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        Music music = musicMapper.selectByPrimaryKey(musicDTO.getId());
        if(music == null) {
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_NOT_EXIST);
        }
        return ResponseDTO.success(CopyUtil.copy(music, MusicDTO.class));
    }

    /**
     * 搜索音乐
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> searchMusic(MusicDTO musicDTO) {
        MusicExample musicExample = new MusicExample();
        if(!CommonUtil.isEmpty(musicDTO.getName())) {
            musicExample.createCriteria().andNameLike("%" + musicDTO.getName() + "%");
        }
        musicExample.setOrderByClause("create_time desc");
        List<Music> musicList = musicMapper.selectByExample(musicExample);
        return ResponseDTO.success(CopyUtil.copyList(musicList, MusicDTO.class));
    }

    /**
     * 音乐播放数增加
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> addMusicListen(MusicDTO musicDTO) {
        if(CommonUtil.isEmpty(musicDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        Music music = musicMapper.selectByPrimaryKey(musicDTO.getId());
        if(music == null) {
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_NOT_EXIST);
        }
        music.setListenNum(music.getListenNum() + 1);
        musicMapper.updateByPrimaryKeySelective(music);
        return ResponseDTO.success(true);
    }

    /**
     * 根据歌单id获取音乐数据
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getMusicListByMusicMenuId(MusicMenuDTO musicMenuDTO) {
        if(CommonUtil.isEmpty(musicMenuDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicMenuItemExample musicMenuItemExample = new MusicMenuItemExample();
        musicMenuItemExample.createCriteria().andMusicMenuIdEqualTo(musicMenuDTO.getId());
        List<MusicMenuItem> musicMenuItemList = musicMenuItemMapper.selectByExample(musicMenuItemExample);
        // 获取当前歌单下所有的音乐id
        List<String> musicIdList = musicMenuItemList.stream().map(MusicMenuItem::getMusicId).collect(Collectors.toList());
        MusicExample musicExample = new MusicExample();
        if(musicIdList.size() > 0) {
            musicExample.createCriteria().andIdIn(musicIdList);
        } else {
            return ResponseDTO.success(new ArrayList<>());
        }
        List<Music> musicList = musicMapper.selectByExample(musicExample);
        return ResponseDTO.success(CopyUtil.copyList(musicList, MusicDTO.class));
    }

    /**
     * 根据歌手id获取音乐数据
     * @param musicDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getMusicListBySingerId(MusicDTO musicDTO) {
        if(CommonUtil.isEmpty(musicDTO.getSingerId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicExample musicExample = new MusicExample();
        musicExample.createCriteria().andSingerIdEqualTo(musicDTO.getSingerId());
        List<Music> music = musicMapper.selectByExample(musicExample);
        return ResponseDTO.success(CopyUtil.copyList(music, MusicDTO.class));
    }

    /**
     * 获取前五个收藏最多的音乐
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getTopFiveCollectMusic() {
        MusicExample musicExample = new MusicExample();
        musicExample.setOrderByClause("collect_num desc");
        PageHelper.startPage(1, 5);
        List<Music> musicList = musicMapper.selectByExample(musicExample);
        List<MusicDTO> musicDTOList = CopyUtil.copyList(musicList, MusicDTO.class);
        return ResponseDTO.success(musicDTOList);
    }

    /**
     * 获取音乐总数
     * @return
     */
    @Override
    public ResponseDTO<Integer> getMusicTotal() {
        return ResponseDTO.success(musicMapper.countByExample(new MusicExample()));
    }

    /**
     * 获取全部音乐数据
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getAllMusicList() {
        List<Music> musicList = musicMapper.selectByExample(new MusicExample());
        return ResponseDTO.success(CopyUtil.copyList(musicList, MusicDTO.class));
    }

    /**
     * 获取前五个最新上架的音乐
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getTopFiveNewMusic() {
        MusicExample musicExample = new MusicExample();
        musicExample.setOrderByClause("create_time desc");
        PageHelper.startPage(1, 5);
        List<Music> musicList = musicMapper.selectByExample(musicExample);
        List<MusicDTO> musicDTOList = CopyUtil.copyList(musicList, MusicDTO.class);
        return ResponseDTO.success(musicDTOList);
    }

    /**
     * 获取前五个播放量最高的音乐
     * @return
     */
    @Override
    public ResponseDTO<List<MusicDTO>> getTopFiveListenMusic() {
        MusicExample musicExample = new MusicExample();
        musicExample.setOrderByClause("listen_num desc");
        PageHelper.startPage(1, 5);
        List<Music> musicList = musicMapper.selectByExample(musicExample);
        List<MusicDTO> musicDTOList = CopyUtil.copyList(musicList, MusicDTO.class);
        return ResponseDTO.success(musicDTOList);
    }
}
